import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: {
      name: 'home'
    }
  },
  {
    name: 'home',
    path: '/home',
    component: () => import('@/view/home.vue'),
    meta: {
      title: '首页',
      keepAlive: true
    }
  },
  {
    name: 'error',
    path: '/error',
    component: () => import('@/view/error.vue'),
    meta: {
      title: '发生错误'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/error'
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory(),
  scrollBehavior() {
    return {
      top: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  const title = to?.meta?.title
  if (title) {
    document.title = title as string
  }
  if (to.matched.length === 0) next('/error')
  next()
})

export default router
